 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ReservarAulaPanel.java
 *
 * Created on 28-nov-2011, 19:15:51
 */
package edu.uoc.tdp.pac4.only5.gui.client.panels.connexio;

import edu.uoc.tdp.pac4.only5.domain.Booking;
import edu.uoc.tdp.pac4.only5.domain.EnumStateBooking;
import edu.uoc.tdp.pac4.only5.domain.Resource;
import edu.uoc.tdp.pac4.only5.domain.Space;
import edu.uoc.tdp.pac4.only5.exceptions.EespaisDatabaseException;
import edu.uoc.tdp.pac4.only5.gui.client.ClientSession;
import edu.uoc.tdp.pac4.only5.gui.client.model.ResourceBookingVOTableModel;
import edu.uoc.tdp.pac4.only5.gui.client.model.ResourceComboBoxModel;
import edu.uoc.tdp.pac4.only5.gui.client.panels.AbstractPanel;
import edu.uoc.tdp.pac4.only5.manager.BookingManager;
import edu.uoc.tdp.pac4.only5.manager.PaymentManager;
import edu.uoc.tdp.pac4.only5.manager.ResourceManager;
import edu.uoc.tdp.pac4.only5.tools.DateTool;
import edu.uoc.tdp.pac4.only5.tools.ResourceBundleTool;
import edu.uoc.tdp.pac4.only5.vo.ResourceBookingVO;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Gerard
 */
public class ReservarAulaPanel extends AbstractPanel {

    private ResourceManager resourceManager;
    private BookingManager bookingManager;
    private PaymentManager paymentManager;
    
    private List<ResourceBookingVO> resourcesSelected;
    private Space space;
    private Date dateStart;
    private Date dateEnd;
    private Long bookingTime;
    private boolean isAllDay;

    /** Creates new form ReservarAulaPanel */
    public ReservarAulaPanel(Space space, ResourceManager resourceManager, BookingManager bookingManager, PaymentManager paymentManager) {
        initComponents();
        this.resourceManager = resourceManager;
        this.bookingManager = bookingManager;
        this.paymentManager = paymentManager;
        this.space = space;
        resourcesSelected = new ArrayList<ResourceBookingVO>();
        setLabels();
        fillList();
    }

    private void fillList() {
        try {
            List<Resource> resources = resourceManager.getNotBookedResources();
            cmbResources.setModel(new ResourceComboBoxModel(resources));
        } catch (RemoteException ex) {
            showErrorMessageDialog(this, "error.generic.rmi");
        } catch(EespaisDatabaseException ex){
            showErrorMessageDialog(this, "error.generic.databaseerror");
            ex.printStackTrace();
        } 
    }

    private void calculateBookingTime() {
        bookingTime = DateTool.getInstance().getTimeBetweenToDates(dateStart, dateEnd);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblDateStart = new javax.swing.JLabel();
        txtDateStart = new javax.swing.JTextField();
        lblDateEnd = new javax.swing.JLabel();
        txtDateEnd = new javax.swing.JTextField();
        lblResources = new javax.swing.JLabel();
        txtTotalPrice = new javax.swing.JTextField();
        lblTotal = new javax.swing.JLabel();
        btnAfegir = new javax.swing.JButton();
        cmbResources = new javax.swing.JComboBox();
        txtQtt = new javax.swing.JTextField();
        lblQtt = new javax.swing.JLabel();
        txtOk1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblResources = new javax.swing.JTable();
        lblReservarAula = new javax.swing.JLabel();
        lblInfoAula = new javax.swing.JLabel();
        chkTotElDia = new javax.swing.JCheckBox();
        btnAfegir1 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        lblDateStart.setText("Date Start");

        txtDateStart.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDateStartFocusLost(evt);
            }
        });

        lblDateEnd.setText("Date End");

        txtDateEnd.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDateEndFocusLost(evt);
            }
        });

        lblResources.setText("Resources");

        txtTotalPrice.setEnabled(false);

        lblTotal.setText("Total Price");

        btnAfegir.setText("+");
        btnAfegir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAfegirActionPerformed(evt);
            }
        });

        lblQtt.setText("Quantitat");

        txtOk1.setText("OK");
        txtOk1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtOk1ActionPerformed(evt);
            }
        });

        tblResources.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tblResources.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblResourcesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblResources);

        lblReservarAula.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        lblReservarAula.setText("Reservar aula:");

        lblInfoAula.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        lblInfoAula.setText("aula id desc");

        chkTotElDia.setText("tot el dia");
        chkTotElDia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkTotElDiaActionPerformed(evt);
            }
        });

        btnAfegir1.setText("-");
        btnAfegir1.setEnabled(false);
        btnAfegir1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAfegir1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 561, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblReservarAula, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblInfoAula, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblResources)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbResources, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(70, 70, 70)
                        .addComponent(lblQtt)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtQtt, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAfegir, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblDateEnd)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(txtDateStart, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtDateEnd, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(chkTotElDia))
                    .addComponent(lblDateStart))
                .addGap(32, 32, 32))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(txtOk1))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(38, 38, 38)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnAfegir1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(287, 287, 287)
                                .addComponent(lblTotal)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtTotalPrice, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 506, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(69, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblReservarAula, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblInfoAula, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(1, 1, 1)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDateStart)
                    .addComponent(txtDateStart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(chkTotElDia))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDateEnd)
                    .addComponent(txtDateEnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblResources)
                    .addComponent(cmbResources, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblQtt)
                    .addComponent(txtQtt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAfegir, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAfegir1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblTotal)
                    .addComponent(txtTotalPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtOk1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(48, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnAfegirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAfegirActionPerformed
        Resource resourceSelected = (Resource) cmbResources.getSelectedItem();
        boolean txtQttIsNotNullOrEmpty = txtQtt.getText() != null && !txtQtt.getText().trim().equals("");
        if (txtQttIsNotNullOrEmpty && resourceSelected != null && resourceSelected.getAmount() > 0 && resourceSelected.getAmount() > Integer.parseInt(txtQtt.getText())) {
            resourcesSelected.add(new ResourceBookingVO(resourceSelected, Integer.parseInt(txtQtt.getText())));
            updateModel();
            updateTotalPrice();
        } else if(!txtQtt.getText().equals("") && resourceSelected.getAmount() < Integer.parseInt(txtQtt.getText())) {
            showErrorMessageDialog(this, "error.nohihatantstock");
        } else {
            showErrorMessageDialog(this, "error.extraresourceselected");
        }
    }//GEN-LAST:event_btnAfegirActionPerformed

    private void txtDateStartFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDateStartFocusLost
        try {
            dateStart = DateTool.getInstance().convertStringToDateWithHourAndMinutes(txtDateStart.getText());
            checkDate(dateStart);
        } catch (ParseException ex) {
            Logger.getLogger(ConsultaAulesPanel.class.getName()).log(Level.SEVERE, null, ex);
            showErrorMessageDialog(this, "error.incorrectdateWithHoursAndMinutes");
        }
    }//GEN-LAST:event_txtDateStartFocusLost

    
    private void checkDate(Date date){
        if(DateTool.getInstance().isEqualOrAfterToday(date)){
            showErrorMessageDialog(this, "error.datebefore");
        }
    }
    
    private void txtDateEndFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDateEndFocusLost
        try {
            dateEnd = DateTool.getInstance().convertStringToDateWithHourAndMinutes(txtDateEnd.getText());
            checkDate(dateEnd);
            calculateBookingTime();
            updateTotalPrice();
        } catch (ParseException ex) {
            showErrorMessageDialog(this, "error.incorrectdateWithHoursAndMinutes");
        }
    }//GEN-LAST:event_txtDateEndFocusLost

    private void chkTotElDiaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkTotElDiaActionPerformed
        isAllDay = chkTotElDia.isSelected();
        txtDateEnd.setEnabled(!isAllDay);
        setAllDayDate();
        updateTotalPrice();
    }//GEN-LAST:event_chkTotElDiaActionPerformed

    private void btnAfegir1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAfegir1ActionPerformed
        ResourceBookingVO resource = resourcesSelected.remove(tblResources.getSelectedRow());
        btnAfegir1.setEnabled(false);
        tblResources.setModel(new ResourceBookingVOTableModel(resourcesSelected, ResourceBundleTool.columnsTableResourceBooking, isAllDay));
        updateTotalPrice();
    }//GEN-LAST:event_btnAfegir1ActionPerformed

    private void tblResourcesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblResourcesMouseClicked
        btnAfegir1.setEnabled(true);
    }//GEN-LAST:event_tblResourcesMouseClicked

    private void txtOk1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtOk1ActionPerformed
        try {
            saveBooking();
        } catch (RemoteException ex) {
            showErrorMessageDialog(this, "error.generic.rmi");
        } catch(EespaisDatabaseException ex){
            showErrorMessageDialog(this, "error.generic.databaseerror");
        } 
    }//GEN-LAST:event_txtOk1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAfegir;
    private javax.swing.JButton btnAfegir1;
    private javax.swing.JCheckBox chkTotElDia;
    private javax.swing.JComboBox cmbResources;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblDateEnd;
    private javax.swing.JLabel lblDateStart;
    private javax.swing.JLabel lblInfoAula;
    private javax.swing.JLabel lblQtt;
    private javax.swing.JLabel lblReservarAula;
    private javax.swing.JLabel lblResources;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JTable tblResources;
    private javax.swing.JTextField txtDateEnd;
    private javax.swing.JTextField txtDateStart;
    private javax.swing.JButton txtOk1;
    private javax.swing.JTextField txtQtt;
    private javax.swing.JTextField txtTotalPrice;
    // End of variables declaration//GEN-END:variables

    @Override
    protected void setLabels() {
        lblDateEnd.setText(getText("dateEnd"));
        lblDateStart.setText(getText("dateStart"));
        lblInfoAula.setText(space.toString());
        lblQtt.setText(getText("qtt"));
        lblReservarAula.setText(getText("reservarAula"));
        lblResources.setText(getText("resources"));
        lblTotal.setText(getText("total"));
    }

    private void updateTotalPrice() {
        Double result = 0D;
        for (ResourceBookingVO resourceBookingVO : resourcesSelected) {
            result += resourceBookingVO.calculatePriceBooked(true);
        }
        
        if(isAllDay){
           result += space.getPriceDay();
        } else {
            result += space.getPriceHour() * bookingTime;
        }

        txtTotalPrice.setText(result.toString());
    }

    private void updateModel() {
        tblResources.setModel(new ResourceBookingVOTableModel(resourcesSelected, ResourceBundleTool.columnsTableResourceBooking, false));
        setTableHeaders(ResourceBundleTool.columnsTableResourceBooking, tblResources);
    }

    private void saveBooking() throws RemoteException, EespaisDatabaseException {
        Booking booking = new Booking();
        booking.setCreationTime(new Date());
        booking.setCustomer(ClientSession.getInstance().getUser().getUserId());
        booking.setEndTime(dateEnd);

        for (ResourceBookingVO resourceBookingVO : resourcesSelected) {
            booking.addExtraResources(resourceBookingVO.getResource());
        }

        booking.setPax(1);
        booking.setRecordDate(new Date());
        booking.setSpace(space.getSpaceId());
        booking.setStartTime(dateStart);
        booking.setStatus(EnumStateBooking.CURSADA.name());
        booking.setTotalPrice(Double.parseDouble(txtTotalPrice.getText()));
        bookingManager.saveBooking(booking);
        booking.setId(bookingManager.getLastValueSequence());
        resourceManager.saveBookedResources(booking);
        paymentManager.newPayment(booking.getId(),Double.parseDouble(txtTotalPrice.getText()));
        showMessageDialog(this, "bookingGrabatOk");
    }

    private void setAllDayDate() {
        if (dateStart != null) {
            dateEnd = DateTool.getInstance().incrementDate(dateStart, 8);
            try {
                txtDateEnd.setText(DateTool.getInstance().convertDateToStringWithHourAndMinutes(dateEnd));
            } catch (ParseException ex) {
                showErrorMessageDialog(this, "error.incorrectdateWithHoursAndMinutes");
            }
        }
    }
}
